import { computed, ComputedRef, ref, Ref, toRaw, unref } from "vue";
import { BasicTableProps, TableRowSelection } from "../types/table";
import { EmitType } from "/#/index";
import { Recordable } from "/#/global";
import { omit } from "lodash-es";
import { findNodeAll } from "@/utils/helper/treeHelper";
import { ROW_KEY } from "../const";

export function useRowSelection(
  propsRef: ComputedRef<BasicTableProps>,
  tableData: Ref<Recordable[]>,
  emit: EmitType
) {
  const selectedRowKeysRef = ref<string[]>([]);
  const selectedRowRef = ref<Recordable[]>([]);

  const getRowSelectionRef = computed((): TableRowSelection | null => {
    const { rowSelection } = unref(propsRef);

    if (!rowSelection) {
      return null;
    }

    return {
      selectedRowKeys: unref(selectedRowKeysRef),
      onChange: (selectedRowKeys: string[] | number[]) => {
        setSelectedRowKeys(selectedRowKeys);
      },
      ...omit(rowSelection, ["onChange"]),
    };

    function setSelectedRowKeys(rowKeys: string[] | number[]) {}
  });

  const getAutoCreateKey = computed(() => {
    return unref(propsRef).autoCreateKey && !unref(propsRef).rowKey;
  });

  const getRowKey = computed(() => {
    const { rowKey } = unref(propsRef);
    return unref(getAutoCreateKey) ? ROW_KEY : rowKey;
  });

  function setSelectedRowKeys(rowKeys: string[]) {
    selectedRowKeysRef.value = rowKeys;
    const allSelectedRows = findNodeAll(
      toRaw(unref(tableData)).concat(toRaw(unref(selectedRowRef))),
      (item) => rowKeys.includes(item[unref(getRowKey) as string]),
      {
        children: propsRef.value.childrenColumnName ?? "children",
      }
    );

    const trueSelectedRows: any[] = [];
    rowKeys.forEach((key: string) => {
      const found = allSelectedRows.find(
        (item) => item[unref(getRowKey) as string] === key
      );
      found && trueSelectedRows.push(found);
    });
    selectedRowRef.value = trueSelectedRows;
  }

  function clearSelectedRowKeys() {
    selectedRowRef.value = [];
    selectedRowKeysRef.value = [];
  }
  function getSelectRowKeys() {
    return unref(selectedRowKeysRef);
  }
  function getRowSelection() {
    return unref(getRowSelectionRef)!;
  }
  return {
    getRowSelection,
    getSelectRowKeys,
    getRowSelectionRef,
    setSelectedRowKeys,
    getRowKey,
    clearSelectedRowKeys,
  };
}
